<template>
  <div class="conter">
    <!-- 音乐播放器 -->
    <!-- :src="getSongPlayUrl(currentAudio?.value.id)" -->
    <audio ref="audioRef" @timeupdate="handleTimeUpdate" @ended="playEndHandler"></audio>
    <div class="timer">
      <span>{{ forMatTime(audioRef?.currentTime! * 1000) }}</span>
    </div>
    <div class="conter_item">
      <!-- 进度条 -->
      <ltSlider v-model="audioCurrentTime" :max="audioTotaoTime" @change="changeHander"></ltSlider>
      <!-- 歌曲切换暂停 -->
      <div class="conter_item_btn">
        <playPrev :size="25" @click="playStore.prevAudio"></playPrev>
        <palyStar v-if="!playStatus" :size="30" @click="changePalyStatusHandler"></palyStar>
        <playEnd v-else :size="30" @click="changePalyStatusHandler"></playEnd>
        <playNext :size="25" @click="playStore.nextAudio"></playNext>
      </div>
    </div>
    <div class="timer">
      <span>{{ forMatTime(audioTotalTime * 1000) }}</span>
    </div>

    <!-- 歌词的弹层 -->
    <ltDrawer v-model="playStore.showLyricDrawer" size="95vh" bgc="#171f34cc">
      <LtLyric ref="lyricRef" :lyric="lyric" @changeAudioTime="changeAudioTime"></LtLyric>
    </ltDrawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue'
import ltSlider from '@renderer/base-ui/lt-slider/index.vue'

import playPrev from '../icon/play-prev.vue'
import playNext from '../icon/play-next.vue'
import palyStar from '../icon/paly-star.vue'
import playEnd from '../icon/play-end.vue'
import LtLyric from './lyric.vue'
import ltDrawer from '@renderer/base-ui/lt-drawer/index.vue'

import getSongPlayUrl from '@renderer/utils/getAudioSrc'

import usePlay from '@renderer/pinia/modules/play'
import createMessage from '@renderer/base-ui/lt-message/message'
import { forMatTime, formatLyric } from '@renderer/utils/format'
import { getLyricApi } from '@renderer/api'

const playStore = usePlay()

// console.log(currentAudio)
const playStatus = ref(false) // 播放状态
const audioTotaoTime = ref(0) // 总时长
const audioCurrentTime = ref(0) // 当前播放时间
const audioTotalTime = ref(0) // 总时长
const isFirstSong = ref(true) // 是否为首次切换当前播放音乐

const audioRef = useTemplateRef<HTMLAudioElement>('audioRef')

// 监听音乐的变化
watch(
  () => playStore.currentAudio,
  (newVal) => {
    if (newVal && audioRef.value) {
      audioRef.value.src = getSongPlayUrl((newVal as any).id)
      audioRef.value.volume = playStore.volume
      audioRef.value
        ?.play()
        .then(() => {
          playStatus.value = true
          playStore.setPlayStatus(playStatus.value)
          audioTotalTime.value = audioRef.value?.duration as any as number
          if (isFirstSong.value) {
            isFirstSong.value = false
            playStatus.value = false
            playStore.setPlayStatus(playStatus.value)
            audioRef.value?.pause()
          }
          audioTotaoTime.value = (audioRef.value?.duration.toFixed(2) as any as number) * 100
        })
        .catch(() => {
          createMessage({ message: '当前歌曲无法播放', type: 'error' })
          playStatus.value = false
          playStore.setPlayStatus(playStatus.value)
        })
    }
  },
  { deep: true }
)

// 监听音量变化
watch(
  () => playStore.volume,
  (newVal) => {
    if (audioRef.value) {
      audioRef.value.volume = newVal
    }
  },
  { immediate: true }
)

// 监听点击头像的变化
watch(
  () => playStore.avatarPlay,
  () => {
    changePalyStatusHandler()
  }
)

// 监听当前播放音乐的变化
const lyric = ref<{ time: number; text: string; active: boolean }[]>([]) // 歌词
watch(
  () => playStore.currentAudio,
  async (newVal) => {
    const res: any = await getLyricApi(newVal.id)
    lyric.value = formatLyric(res.lrc.lyric)
    console.log(lyric.value)
  }
)

// 改变播放状态
const changePalyStatusHandler = () => {
  if (playStatus.value) {
    audioRef.value?.pause()
    playStatus.value = false
  } else {
    playStatus.value = true
    audioRef.value?.play().catch(() => {
      playStatus.value = false
    })
  }
  playStore.setPlayStatus(playStatus.value)
}
const keyChangePalyStatusHandler = (e: KeyboardEvent) => {
  if (e.code === 'Space') {
    changePalyStatusHandler()
  }
}
onMounted(() => {
  document.addEventListener('keydown', keyChangePalyStatusHandler)
})
onUnmounted(() => {
  document.removeEventListener('keydown', keyChangePalyStatusHandler)
})

// 监听音乐的播放
const lyricRef = useTemplateRef('lyricRef')
const handleTimeUpdate = () => {
  audioCurrentTime.value = (audioRef.value?.currentTime.toFixed(2) as any as number) * 100
  lyricRef.value?.changeLyricHandler(audioCurrentTime.value / 100)
}

// 松开进度条
const changeHander = (val: number) => {
  if (audioRef.value) {
    audioRef.value.currentTime = (val / 100).toFixed(2) as any as number
  }
}

// 播放结束切换下一首
const playEndHandler = () => {
  playStore.nextAudio()
}

// 点击歌词改变播放时间
const changeAudioTime = (time: number) => {
  if (audioRef.value) {
    audioRef.value.currentTime = time
  }
}
</script>

<style scoped lang="scss">
.conter {
  flex: 1;
  height: 100%;
  display: flex;
  justify-content: center;

  .timer {
    font-size: 14px;
    display: flex;
    flex-direction: column;
    margin: 7px 15px;
  }

  .conter_item {
    width: 80%;
    height: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;

    .conter_item_btn {
      display: flex;
      margin-top: 10px;
      justify-content: center;
      align-items: center;
      /* background-color: red; */
    }
  }
}
</style>
